<template>
    <!--加工验收修改 -->
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div
            class="tabs warningTabs"
            v-if="Object.keys(formData).length != 0"
        >
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="验收明细"
                    name="receivingMaterials"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="服务费用"
                    name="transportationCharge"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        ref="formDataRef"
                                        :rules="formDataRules"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收编号"
                                                    prop="billNo"
                                                >
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="所属机构"
                                                    prop="orgName"
                                                >
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="收料类型"
                                                    prop="receivingType"
                                                >
                                                    <el-radio-group
                                                        v-model="
                                                            formData.receivingType
                                                        "
                                                        disabled
                                                    >
                                                        <el-radio :label="0"
                                                            >普通加工</el-radio
                                                        >
                                                        <el-radio :label="1"
                                                            >砼加工</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收日期"
                                                    prop="acceptanceDate"
                                                >
                                                   {{formData.acceptanceDate}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="是否计加工费"
                                                    prop="isIncludingProcessingFee"
                                                >
                                                    <el-radio-group
                                                        v-model="
                                                            formData.isIncludingProcessingFee
                                                        "
                                                        disabled
                                                    >
                                                        <el-radio :label="1"
                                                            >是(外部加工)</el-radio
                                                        >
                                                        <el-radio :label="0"
                                                            >否(自行加工)</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="采购人员"
                                                    prop="purchaserName"
                                                >
                                                    {{
                                                        formData.purchaserName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="加工单位"
                                                    prop="processingUnitName"
                                                >
                                                    {{formData.processingUnitName}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <!-- 是否计加工费的值为: 是(外部加工,才显示该字段) -->
                                                <el-form-item
                                                    label="加工合同"
                                                    v-show="
                                                        formData.isIncludingProcessingFee
                                                    "
                                                >
                                                <span>
                                                    {{formData.contractName}}
                                                    <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                contractNoClick
                                                            "
                                                            v-if="formData.contractName"
                                                        ></i>
                                                </span>

                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                   {{formData.taxRate}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="验收人员"
                                                    prop="acceptancerName"
                                                >
                                                   {{formData.acceptancerName}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 汇总验收明细的清单税额累计 -->
                                                <el-form-item
                                                    label="税额"
                                                    prop="taxAmount"
                                                >
                                                  {{formData.taxAmount}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="服务费用(元)"
                                                    prop="freight"
                                                >
                                                    {{
                                                        formData.freight
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <!-- 收料类型为【普通加工】显示“原材料来源” -->
                                                <el-form-item
                                                    label="原材料来源"
                                                    :prop="
                                                        !formData.receivingType
                                                            ? 'sourceOfRawMaterials'
                                                            : 'sourceOfRawMaterialss'
                                                    "
                                                    v-show="
                                                        !formData.receivingType
                                                    "
                                                >
                                                   <el-radio-group
                                                        v-model="
                                                            formData.sourceOfRawMaterials
                                                        "
                                                        disabled
                                                    >
                                                        <el-radio :label="1"
                                                            >购买</el-radio
                                                        >
                                                        <el-radio :label="2"
                                                            >自有</el-radio
                                                        >
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="加工验收金额(元)"
                                                    prop="acceptanceAmount"
                                                >
                                                    {{
                                                        formData.acceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税价合计"
                                                    prop="totalAmount"
                                                >
                                                    <!-- <el-input
                                    placeholder="请填写"
                                    v-model="formData.totalAmount"
                                ></el-input> -->
                                                    {{
                                                        formData.totalAmount
                                                    }}
                                                    元
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currencyId"
                                                >
                                                   {{formData.currency}}

                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{
                                                        formData.baseCurName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                    prop="baseCurRate"
                                                >
                                                    {{formData.baseCurRate}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <!-- <el-col :span="12">
                                                <el-form-item
                                                    label="验收金额(本位币)"
                                                    prop="baseCurAcceptanceAmount"
                                                >
                                                    {{
                                                        formData.baseCurAcceptanceAmount
                                                    }}
                                                </el-form-item>
                                            </el-col> -->
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="状态"
                                                    prop="state"
                                                >
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传财务共享"
                                                    prop=""
                                                >
                                                    {{ formData.easId ? '已传' : '未传'}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12" v-if="formData.redBillState !== -1">
                                                <el-form-item
                                                    label="冲红单"
                                                    prop=""
                                                >
                                                     <span
                                                        :style="
                                                            redBillStateStyle
                                                        "
                                                        >{{
                                                            redBillStateFun
                                                        }}</span
                                                    >
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注">
                                                {{formData.remarks}}
                                            </el-form-item>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item label="作废人：">
                                                    <span>{{
                                                        formData.nullifyCreator
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废原因："
                                                >
                                                    <span>{{
                                                        formData.nullifyReason
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废说明："
                                                >
                                                    <span>{{
                                                        formData.nullifyDescription
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废时间："
                                                >
                                                    <span>{{
                                                        formData.nullifyCreated
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 验收明细 -->

                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            验收明细
                        </div>

                        <!-- 验收明细的tab标签页 -->
                        <div class="tabs-content">
                            <el-tabs
                                v-model="acceptanceDetailsTabs"
                                :class="'childTab ' + childTabClass"
                                tab-position="left"
                                @tab-click="onChangeTab"
                            >
                                <el-tab-pane
                                    label="加工费"
                                    name="processingFee"
                                    :disabled="clickTabFlag"
                                ></el-tab-pane>
                                <el-tab-pane
                                    label="成品明细"
                                    name="finishedProductDetails"
                                    :disabled="clickTabFlag"
                                ></el-tab-pane>
                                <el-tab-pane
                                    label="原物资"
                                    name="rawMaterials"
                                    :disabled="clickTabFlag"
                                ></el-tab-pane>
                                <div>
                                    <div id="receivingMaterialsCon">
                                        <div
                                            class="tabs-title"
                                            id="processingFee"
                                        >
                                            加工费
                                        </div>
                                        <div class="e-table">
                                            <div
                                                class="errorMsg"
                                                v-if="
                                                    errorProcessingFeeMsg.length >
                                                    0
                                                "
                                            >
                                                <span>
                                                    {{
                                                        errorProcessingFeeMsg.join(
                                                            ','
                                                        )
                                                    }}
                                                </span>
                                            </div>
                                            <el-table
                                                :data="processingFeeData"
                                                ref='processingFeeTable'
                                                border
                                                style="width: 100%"
                                                @cell-mouse-enter="
                                                    cellMouseEnter
                                                "
                                                @cell-mouse-leave="
                                                    cellMouseLeave
                                                "
                                                :cell-class-name="cellClsNm"
                                                :header-cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren'
                                                }"
                                                row-key="uuid"
                                                :max-height="$store.state.tableHeight"
                                                v-sortTable="{ 'tableData': processingFeeData, '_this': this, 'ref': 'processingFeeTable' }"
                                            >

                                                <el-table-column
                                                    prop="materialClassName"
                                                    label="物资类别"
                                                    min-width="170"
                                                    fixed
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="materialName"
                                                    label="物资名称"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="spec"
                                                    label="规格"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="texture"
                                                    label="材质"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="unit"
                                                    label="单位"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="warehouseName"
                                                    label="仓库"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop='quantity'
                                                    label="数量"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="price"
                                                    label="加工单价（元）"
                                                    width="130"
                                                >
                                                </el-table-column>

                                                <el-table-column
                                                    prop="amount"
                                                    label="金额（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </div>
                                    <div id="receivingMaterialsCon">
                                        <div
                                            class="tabs-title"
                                            id="finishedProductDetails"
                                        >
                                            成品明细
                                        </div>
                                        <div class="e-table">
                                            <div
                                                class="errorMsg"
                                                v-if="
                                                    errorFinishedProductMsg.length >
                                                    0
                                                "
                                            >
                                                <span>
                                                    {{
                                                        errorFinishedProductMsg.join(
                                                            ','
                                                        )
                                                    }}
                                                </span>
                                            </div>
                                            <el-table
                                                :data="finishedProductData"
                                                ref='finishedProductTable'
                                                border
                                                style="width: 100%"
                                                @cell-mouse-enter="
                                                    cellMouseEnter
                                                "
                                                @cell-mouse-leave="
                                                    cellMouseLeave
                                                "
                                                :cell-class-name="cellClsNm"
                                                :header-cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren'
                                                }"
                                                row-key="uuid"
                                                :max-height="$store.state.tableHeight"
                                                v-sortTable="{ 'tableData': finishedProductData, '_this': this, 'ref': 'finishedProductTable' }"
                                            >

                                                <el-table-column
                                                    prop="materialClassName"
                                                    label="物资类别"
                                                    min-width="170"
                                                    fixed
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="materialName"
                                                    label="物资名称"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="spec"
                                                    label="规格"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="texture"
                                                    label="材质"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="unit"
                                                    label="单位"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="warehouseName"
                                                    label="仓库"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="quantity"
                                                    label="数量"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="price"
                                                    label="成品单价（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="amount"
                                                    label="金额（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="apportionedFreight"
                                                    label="分摊服务费（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="totalAmortizationRatio"
                                                    label="总摊销比例%"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="amortizationMonth"
                                                    label="摊销月"
                                                    width="100"
                                                >
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </div>
                                    <div id="receivingMaterialsCon">
                                        <div
                                            class="tabs-title"
                                            id="rawMaterials"
                                        >
                                            原物资
                                        </div>
                                        <div class="e-table">

                                            <div
                                                class="errorMsg"
                                                v-if="
                                                    errorRawMaterialsMsg.length >
                                                    0
                                                "
                                            >
                                                <span>
                                                    {{
                                                        errorRawMaterialsMsg.join(
                                                            ','
                                                        )
                                                    }}
                                                </span>
                                            </div>
                                            <el-table
                                                :data="rawMaterialsData"
                                                ref='rawMaterialsTable'
                                                border
                                                style="width: 100%"
                                                @cell-mouse-enter="
                                                    cellMouseEnter
                                                "
                                                @cell-mouse-leave="
                                                    cellMouseLeave
                                                "
                                                :row-class-name="
                                                    tableRowClassName
                                                "
                                                :cell-class-name="cellClsNm"
                                                :header-cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :cell-style="{
                                                    textAlign: 'center'
                                                }"
                                                :tree-props="{
                                                    children: 'children',
                                                    hasChildren: 'hasChildren'
                                                }"
                                                row-key="uuid"
                                                :max-height="$store.state.tableHeight"
                                                v-sortTable="{ 'tableData': rawMaterialsData, '_this': this, 'ref': 'rawMaterialsTable' }"
                                            >

                                                <el-table-column
                                                    prop="materialClassName"
                                                    label="类别"
                                                    min-width="250"
                                                    fixed
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="materialName"
                                                    label="物资名称"
                                                    min-width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="spec"
                                                    label="规格"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="texture"
                                                    label="材质"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="unit"
                                                    label="单位"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="warehouseName"
                                                    label="仓库"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="receivedQuantity"
                                                    label="领用数量"
                                                    width="100"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="offsetInventoryQuantity"
                                                    label="冲库存数量"
                                                    width="130"
                                                >
                                                </el-table-column>
                                                <el-table-column
                                                    prop="price"
                                                    label="采购单价（元）"
                                                    width="130"
                                                >
                                                </el-table-column>

                                                <el-table-column
                                                    prop="amount"
                                                    label="金额（元）"
                                                    width="130"
                                                >
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </div>
                                </div>
                            </el-tabs>
                        </div>
                    </div>

                    <!-- 服务费用 -->
                    <div id="transportationChargeCon" class="con">
                        <div class="tabs-title" id="transportationCharge">
                            服务费用
                        </div>
                        <div class="e-table">
                            <!-- <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="mini"
                                            class="btn-blue"
                                            @click="addRowClick"
                                            >新增行</el-button
                                        >
                                        <el-button size="mini">删除</el-button>
                                    </div>
                                </div>
                            </div> -->
                            <div
                                class="errorMsg"
                                v-if="errorServiceFeeMsg.length > 0"
                            >
                                <span>
                                    {{ errorServiceFeeMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="serviceFeeData"
                                ref='serviceFeeTable'
                                border
                                style="width: 100%"
                                @selection-change="serviceFeeSelect"
                                @cell-mouse-enter="cellMouseEnterF"
                                @cell-mouse-leave="cellMouseLeaveF"
                                :row-class-name="tableRowClassNameF"
                                :cell-class-name="cellClsNm"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': serviceFeeData, '_this': this, 'ref': 'serviceFeeTable' }"
                            >
                                <el-table-column type="selection" width="55">
                                </el-table-column>
                                <el-table-column
                                    fixed
                                    label="合同编号"
                                    min-width="150"
                                    prop='contractBillNo'
                                >

                                </el-table-column>
                                <el-table-column
                                    label="结算单位"
                                    min-width="190"
                                    fixed
                                    prop='settlementUnitName'
                                >

                                </el-table-column>

                                <el-table-column
                                    prop="contractDtlName"
                                    label="清单名称"
                                    width="100"
                                >

                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="数量"
                                    width="100"
                                >

                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="金额(元)"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="发票编号"
                                    width="130"
                                    prop='invoiceNo'
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="taxRate"
                                    label="税率%"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="taxAmount"
                                    label="税额(元)"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="totalAmount"
                                    label="税价合计(元)"
                                    width="130"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="materialsettle"
                            v-if="objFlag.flag5"
                            :isView='true'
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <AcceptanceHistory
                            :billType="1016"
                            :billId="billid"
                            @historyTableHeight='historyTableHeight'
                        ></AcceptanceHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="
                    formData.state == 1 ||
                    formData.state == 9 ||
                    formData.state == 2
                "
                >打印</el-button
            > -->
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="
                    formData.state === 2 &&
                    (formData.redBillState === '' ||
                        formData.redBillState === -1)
                "
                @click="redSingle"
                >冲红单</el-button
            >
            <exaButtons :auditState="auditState" @exas="exas" v-if="formData.state !== 5" :state='formData.state' :founderId='formData.founderId' :multiple="formData.state === 1 || formData.state === 2" :commandList='commandList'></exaButtons>

            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import {
    showPromptPop,
    showSuccessPop,
    showLoading,
    hideLoading,
    getUuid,
    openAppClient
} from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import processingRequest from '@/api/materials/processingAcceptance'
import request from '@/api/materials/materialAcceptance'
import exaButtons from '@/components/common/exaButtons'
import AcceptanceHistory from '@/pages/materialsmanagement/checkAdmin/AcceptanceHistory'
import { webprintReport, numToChinese } from '@/utils/common'

export default {
    components: {
        AttachComp,
        exaButtons,
        AcceptanceHistory
    },
    data () {
        return {
            tabsName: 'baseInfo',
            clickId: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            formData: {
                billNo: '', //验收编号
                orgName: '', //所属机构
                isIncludingProcessingFee: '', //是否计加工费
                acceptanceDate: '', //验收日期
                receivingType: '', //收料类型
                purchaserName: '', //采购人员
                processingUnitName: '', //加工单位
                acceptancerName: '', //验收人员
                taxRate: '', //税率%
                freight: '', //运输单位费用
                taxAmount: '', //税额
                currency: '', //币种
                acceptanceAmount: '', //加工验收金额
                showEas: '', //传财务共享
                totalAmount: '', //税价合计
                baseCurAcceptanceAmount: '', //验收金额(本位币)
                baseCurName: '', //本位币
                state: '', //状态
                remarks: '', //备注
                acceptanceQuantity: 0,
                acceptancerId: '',
                baseCurFreight: 0,
                baseCurId: '',
                baseCurRate: 0,
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                businessType: 0,
                currencyId: '',
                easId: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                isAccepSettle: true,
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                purchaserId: '',
                purchasingUnitId: '',
                purchasingUnitName: '',
                redBillState: '',
                rmbAcceptanceAmount: 0,
                rmbFreight: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settleId: '',
                settleNo: '',
                sourceBillId: '',
                sourceBillNo: '',
                sourceId: '',
                sourceNumber: '',
                supplierId: '',
                supplierName: '',
                workId: '',
                contractId: '',
                contractName: '',
                contractNo: '',
                processingUnitId: '',
                sourceOfRawMaterials: 0
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            formDataRules: {
                receivingType: [
                    {
                        required: true,
                        message: '请选择收料类型',
                        trigger: 'blur'
                    }
                ],
                // acceptanceDate: [
                //     {
                //         required: true,
                //         message: '请选择验收日期',
                //         trigger: 'blur'
                //     }
                // ],
                isIncludingProcessingFee: [
                    {
                        required: true,
                        message: '请选择是否计加工费',
                        trigger: 'blur'
                    }
                ],
                purchaserName: [
                    {
                        required: true,
                        message: '采购人员是必填项',
                        trigger: 'blur'
                    }
                ],
                processingUnitName: [
                    {
                        required: true,
                        message: '请选择加工单位',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    {
                        required: true,
                        message: '请填写税率',
                        trigger: 'blur'
                    }
                ],
                taxAmount: [
                    {
                        required: true,
                        message: '请填写税额',
                        trigger: 'blur'
                    }
                ],
                acceptanceAmount: [
                    {
                        required: true,
                        message: '加工验收金额为必填项',
                        trigger: 'blur'
                    }
                ],
                totalAmount: [
                    {
                        required: true,
                        message: '请填写税价合计',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    {
                        required: true,
                        message: '请选择币种',
                        trigger: 'blur'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '本位币为必填项',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ],
                // baseCurAcceptanceAmount: [
                //     {
                //         required: true,
                //         message: '验收金额(本位币)为必填项',
                //         trigger: 'blur'
                //     }
                // ],
                sourceOfRawMaterials: [
                    {
                        required: true,
                        message: '请选择原材料来源',
                        trigger: 'blur'
                    }
                ],
                freight: [
                    {
                        required: true,
                        message: '请输入服务费用',
                        trigger: 'blur'
                    }
                ]
            },
            auditState: {},
            auditParams: {
                // 审核
                billId: '',
                billType: '1016',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1016',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            acceptanceDetailsTabs: 'processingFee',
            childTabClass: '',
            processingFeeData: [], // 加工费
            finishedProductData: [], // 成品明细
            rawMaterialsData: [], // 原物资
            serviceFeeData: [], // 服务费
            errorList: [], //控制导航栏感叹号的显示
            tabArr: [],
            errorProcessingFeeMsg: [], // 验收明细-加工费
            errorFinishedProductMsg: [], // 验收明细-成品明细
            errorRawMaterialsMsg: [], // 验收明细-原物资
            errorServiceFeeMsg: [], // 服务费用
            processingUnited: {
                materials: [],
                processingUnitId: ''
            },
            selectStockQuery: {
                orgId: '',
                unitId: '',
                keyWord: '',
                stockType: '2'
            },
            addRow: {
                amount: 0,
                billId: '',
                changeType: 0,
                contractBillId: '',
                contractBillNo: '',
                contractDtlId: '',
                contractDtlName: '',
                dtlId: '',
                invoiceNo: '',
                price: 0,
                quantity: 0,
                settlementUnitId: '',
                settlementUnitName: '',
                taxAmount: 0,
                taxRate: 0,
                totalAmount: 0
            },
            isBaseCurRate: true,
            inStockList: [],
            selectStocked: '选择库存',
            jsdwData: {
                businessUnitTypes: [],
                keyword: '',
                limit: 10,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: null
            },
            jsdwIds: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            historyData: [],
            commandList: [
                { key: 1, value: '委外加工物资验收单' },
                { key: 2, value: '成品物资明细' },
                { key: 3, value: '加工物资服务费验收单' }
            ],
            serviceFeeList: []
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        // //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },

        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 100 - this.lastConHeight
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }

    },
    watch: {
        'formData.receivingType' () {
            // 如果收料类型为【普通加工】,原材料来源必选, 如果收料类型为【砼加工】,则非必选,并清除提示信息
            if (this.formData.receivingType) {
                this.$refs.formDataRef.clearValidate(
                    'sourceOfRawMaterials'
                )
                this.formData.sourceOfRawMaterials = ''
            }
        },
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurRate = null
                }
            }
        },
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
        finishedProductData () {
            console.log(this.finishedProductData)
            this.finishedProductData.forEach(item => {
                this.inStockList = item.children.map(itm => itm)
            })
            console.log(this.inStockList)
        },
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },

    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.selectStockQuery.orgId = this.orgId
        this.getBasicData() //进入页面就获取基本信息数据
        this.getProcessingFeeData() // 加工费
        this.getFinishedProductData() // 成品明细
        this.getRawMaterialsData() // 原物资
        this.getServeList() // 服务费用
        this.getAttach() // 获取附件列表
        this.getUnitInfo() // 获取按钮状态
        // this.getDetailsData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            [
                'receivingMaterials',
                'processingFee',
                'finishedProductDetails',
                'rawMaterials'
            ],
            'transportationCharge',
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag && arr.find(i => i === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(
                            item[0]
                        ).offsetHeight
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop + 20
                            } else {
                                return (
                                    document.getElementById(x).offsetTop + 20 +
                                    prevHeight +
                                    document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop + 20
                        return itemTop
                    }
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 20 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 50 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 50 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.acceptanceDetailsTabs = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector(
                        '.childTab .el-tabs__nav'
                    )
                        ? document.querySelector('.childTab .el-tabs__nav')
                            .offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight =
                        document.getElementById(item[0]).offsetHeight +
                        document.getElementById(item[0]).nextSibling
                            .offsetHeight
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                                prevHeight +
                                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //获取基本信息数据
        async getBasicData () {
            this.formData = await processingRequest.getbasicInfo(
                this.billid
            )

            // 开启验收金额(元)的监听
            this.$watch('formData.acceptanceAmount', () => {
                // 税价合计 = 验收金额 + 税额
                this.formData.totalAmount =
                    +this.formData.acceptanceAmount *
                    +this.formData.taxAmount
                // 验收金额(本位币) = 验收金额 * 本位币汇率
                this.formData.baseAcceptanceAmount =
                    +this.formData.acceptanceAmount *
                    +this.formData.baseCurRate
            })
            // 监听税额
            this.$watch('formData.taxAmount', () => {
                // 税价合计 = 验收金额+税额
                this.formData.totalAmount =
                    +this.formData.acceptanceAmount +
                    +this.formData.taxAmount
            })
        },
        // 本位币汇率失去焦点时
        baseCurRateBlur () {
            if (this.formData.baseCurRate == 0) {
                this.formData.baseCurRate = null
            }
            this.formData.baseCurAcceptanceAmount =
                +this.formData.acceptanceAmount *
                +this.formData.baseCurRate
        },
        // 当币种切换时,获取人民币汇率
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
        },
        // 点击加工单位后面的选择源单
        async processingUnitNameClick () {
            //     this.formData.isIncludingProcessingFee = val[0] // 是否计加工费(0:否;1:是)
            //     this.formData.processingUnitName = val[0] // 加工单位
            //     this.formData.contractName = val[0] // 加工合同
            //     this.formData.purchaserName = val[0] // 采购人员名称
            //     this.formData.taxRate = val[0] // 税率,根据加工收料带入加工合同税率
            //     this.formData.currency = val[0] // 币种
            // })
            // let data = await processingRequest.selectSource(
            //     {
            //         receivingType: this.formData.receivingType
            //     },
            //     this.processingUnited
            // )
            // this.setSelectedInfo(data)
            let data = await processingRequest.selectSource({
                orgId: this.orgId,
                receivingType: this.formData.receivingType,
                parentId: '',
                keyWord: ''
            })
            // openAppClient('/showSelectedData', '选择结果')
            Object.assign(
                this.$data.processingUnited,
                this.$options.data().processingUnited
            )
            this.formData.processingUnitName = data[0].processingUnitName // 加工单位
            this.formData.processingUnitId = data[0].processingUnitId // 加工单位Id
            this.formData.contractName = data[0].contractName // 加工合同
            this.formData.purchaserName = data[0].purchasingPersonnelName // 采购人员名称
            // this.formData.taxRate = data[0] // 税率,根据加工收料带入加工合同税率
            // this.formData.currency = data[0] // 币种

            const newArr = []
            let obj = {}
            data.forEach(item => {
                const topClassName = item.materialClassName.split('/')[0]
                const topClassId = item.materialClassId.split('/')[0]
                obj = {
                    topClassId,
                    topClassName,
                    customId: topClassId,
                    materialClassId: topClassId,
                    materialClassName: topClassName,
                    uuid: getUuid(),
                    totalAmount: null,
                    totalQuantity: null,
                    children: []
                }
                if (newArr.length < 1) {
                    newArr.push(obj)
                } else {
                    newArr.forEach(itm => {
                        if (itm.topClassId !== topClassId) {
                            newArr.push(obj)
                        }
                    })
                }

                newArr.forEach(its => {
                    let nums = processingRequest.getUuid()
                    its.children.push({
                        uuid: getUuid(),
                        customId: getUuid(),
                        billId: this.billid, //	验收ID
                        changeType: 1, //变更类型
                        dtlId: nums[0], //验收明细ID
                        materialClassId: item.materialClassId
                            .split('/')
                            .slice(1, 3)
                            .join('/'), //物资类别id
                        materialClassName: item.materialClassName
                            .split('/')
                            .slice(1, 3)
                            .join('/'), // 物资类别名称
                        materialId: item.materialId, //物资id
                        materialName: item.materialName, //物资名称
                        sourceDtlId: item.dtlId, //源单明细id
                        spec: item.spec, //规格型号
                        texture: item.texture, //材质
                        unit: item.unit, //计量单位
                        warehouseId: item.warehouseId, //仓库id
                        warehouseName: item.warehouseName,
                        price: 0, // 加工单价
                        amount: 0, // 金额
                        quantity: item.quantity, //数量
                        notAcceptedQuantity: item.unAcceptedQuantity, // 未验收数量
                        amortizationMonth: 0, //摊销月
                        apportionedFreight: 0, // 分摊服务费
                        materialType: item.materialType, //物资类型
                        totalAmortizationRatio: 0 //总摊销比例(%)
                    })
                    this.processingUnited.materials.push({
                        materialClassId: item.materialClassId
                            .split('/')
                            .slice(1, 3)
                            .join('/'),
                        materialId: item.materialId,
                        texture: item.texture
                    })
                    // 统计小计
                    const count = its.children.reduce(
                        (prev, c) => (prev += c.amount || 0),
                        0
                    ).toFixed(2)
                    its.materialName = `金额小计： ${count}`
                })
            })
            console.log(newArr)
            console.log(this.processingUnited)
            this.processingUnited.processingUnitId =
                this.formData.processingUnitId

            // 加工费
            this.processingFeeData = newArr
            // 成品明细
            this.finishedProductData = newArr
        },
        // 点击选择验收人员
        async acceptancerNameClick () {
            let data = await processingRequest.institutionalStaff({
                page: 10,
                limit: 1,
                orgId: this.orgId
            })
            this.formData.acceptancerId = data[0].userId
            this.formData.acceptancerName = data[0].userName
        },
        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },
        contractNoClick () {
            // 弹出合同详细页面
            openAppClient(`/processingContractApplyShow?billid=${this.formData.contractId}&isview=${true}`, '加工合同查看')
        },
        //获取验收明细-加工费
        async getProcessingFeeData () {
            let res = await processingRequest.getProcessingFeeData(this.billid)
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = item.children.reduce(
                    (prev, c) => (prev += c.amount || 0),
                    0
                ).toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            this.processingFeeData = res
        },
        //获取验收明细-成品明细
        async getFinishedProductData () {
            let res = await processingRequest.getFinishedProductData(
                this.billid
            )
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = item.children.reduce(
                    (prev, c) => (prev += c.amount || 0),
                    0
                ).toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            this.finishedProductData = res
        },

        // 监听加工费数量
        quantityInput (row) {
            if (row.changeType == 1) {
                row.changeType == 1
            } else {
                row.changeType = 2
            }

            if (
                row.notAcceptedQuantity &&
                row.quantity > row.notAcceptedQuantity
            ) {
                row.quantity = ''
                row.price = 0
            } else {
                if (!!row.amount && !!row.quantity) {
                    row.price = (+row.amount / +row.quantity).toFixed(2)
                }
            }
            this.finishedProductData.forEach(item => {
                if (row.materialId == item.materialId) {
                    item.quantity = row.quantity
                }
            })
        },

        // 监听加工费金额
        amountBlur (row) {
            if (row.changeType == 1) {
                row.changeType == 1
            } else {
                row.changeType = 2
            }
            if (!!row.quantity && !!row.amount) {
                row.price = (+row.amount / +row.quantity).toFixed(2)
            }
        },
        // 成品明细-数量
        finishedProductQuantityInput (row) {
            if (
                row.notAcceptedQuantity &&
                row.quantity > row.notAcceptedQuantity
            ) {
                row.quantity = ''
                row.price = 0
            } else {
                if (!!row.amount && !!row.quantity) {
                    row.price = +row.amount / +row.quantity
                }
            }
            this.processingFeeData.forEach(item => {
                if (row.materialId == item.materialId) {
                    item.quantity = row.quantity
                }
            })
        },
        // 总摊销比例%
        totalAmortizationRatioBlur (row) {
            if (row.totalAmortizationRatio == 0) {
                row.totalAmortizationRatio = ''
            }
        },
        // 摊销月
        amortizationMonthBlur (row) {
            if (row.amortizationMonth == 0) {
                row.amortizationMonth = ''
            }
        },
        // 原物资-冲库存数量
        offsetInventoryQuantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType == 1
            } else {
                row.changeType = 2
            }
            if (
                row.receivedQuantity &&
                row.offsetInventoryQuantity > row.receivedQuantity
            ) {
                row.offsetInventoryQuantity = ''
            }
        },
        // 获取原物资的表格数据
        async getRawMaterialsData () {
            let res = await processingRequest.getRawMaterialsData(this.billid)
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = item.children.reduce(
                    (prev, c) => (prev += c.amount || 0),
                    0
                ).toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            this.rawMaterialsData = res
        },

        // 原物资-选择库存
        async selectStock (obj1) {
            console.log(obj1)
            this.selectStocked = obj1.materialName

            // this.selectStockQuery.unitId = this.formData.processingUnitId
            this.selectStockQuery.unitId = '1503177344080867329'
            // this.selectStockQuery.orgId = '1439990097591140358'
            let data = await processingRequest.selectStock(
                this.selectStockQuery
            )
            // openAppClient('/showSelectedData', '选择结果', function () {
            //     alert(data)
            // })

            const newArr = this.rawMaterialsData
            let obj = {}

            data.forEach(item => {
                // const topClassName = item.materialClassName.split('/')[0]
                // const topClassId = item.materialClassId.split('/')[0]
                obj = {
                    topClassId: obj1.materialId,
                    topClassName: obj1.materialName,
                    customId: obj1.materialId,
                    materialClassId: obj1.materialId,
                    materialClassName: obj1.materialName,
                    uuid: getUuid(),
                    totalAmount: null,
                    totalQuantity: null,
                    children: []
                }
                if (newArr.length < 1 && this.rawMaterialsData.length < 1) {
                    newArr.push(obj)
                } else {
                    let isPush = this.rawMaterialsData.every(
                        i => i.materialClassId !== obj.materialClassId
                    )
                    if (isPush) {
                        newArr.push(obj)
                    }
                }
                console.log(this.rawMaterialsData)
                newArr.forEach(its => {
                    let result = {
                        uuid: getUuid(),
                        customId: getUuid(),
                        billId: this.billid, //	验收ID
                        changeType: 1, //变更类型
                        dtlId: '', //原物资明细id
                        finishedGoodsDtlId: obj1.dtlId,
                        materialClassId: item.materialClassId, //物资类别id
                        materialClassName: item.materialClassName, // 物资类别名称
                        materialId: item.materialId, //物资id
                        materialName: item.materialName, //物资名称
                        offsetInventoryQuantity: '', // 冲库存数量
                        receivedQuantity: item.quantity, // 领用数量
                        spec: item.spec, //规格型号
                        texture: item.texture, //材质
                        unit: item.unit, //计量单位
                        warehouseId: item.warehouseId, //仓库id
                        warehouseName: item.warehouseName,
                        price: 0, // 采购单价
                        amount: 0 // 金额
                    }
                    if (its.children.length < 1) {
                        its.children.push(result)
                    } else {
                        if (result.materialId) {
                            its.children.forEach(m => {
                                if (m.materialId !== result.materialId) {
                                    its.children.push(result)
                                }
                            })
                        }
                    }

                    // 统计小计
                    const count = its.children.reduce(
                        (prev, c) => (prev += c.amount || 0),
                        0
                    ).toFixed(2)
                    its.materialName = `金额小计： ${count}`
                })
            })
            console.log(newArr)

            this.rawMaterialsData = newArr
            console.log(this.rawMaterialsData)
        },

        // 删除
        rawMaterialsDelete (row) {
            row.changeType = -1
            console.log(123)
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        // ---------------------------------服务费用-----------------------------------
        // 点击服务费用的新增行
        addRowClick () {
            this.serviceFeeData.push(this.addRow)
            console.log(this.serviceFeeData)
        },
        // 获取服务费用表格数据
        async getServeList () {
            let res = await processingRequest.getServeList(this.billid)
            if (Array.isArray(res)) {
                this.serviceFeeData = res
            }
        },
        // 合同编号
        async contractDialog (row, index) {
            let contracted = {
                contractId: row.contractBillId,
                contractType: row.contractBillType || 0
            }

            let res = await request.getContract(
                { orgid: this.orgId },
                contracted
            )
            this.setSelectedInfo(res)
            // openAppClient('/showSelectedData', '选择结果')
            let result
            // 如果选择的是合同并且合同下有清单,则需带入合同下的清单
            if (res.list && res.list.length > 0) {
                result = res.list.map(item => {
                    return {
                        amount: 0,
                        billId: this.billid,
                        changeType: 1,
                        contractBillId: res.contractId,
                        contractBillNo: res.contractNumber,
                        contractDtlId: '',
                        contractDtlName: item.name,
                        dtlId: '',
                        invoiceNo: '',
                        price: 0,
                        quantity: item.quantity,
                        settlementUnitId: res.secondPartyId,
                        settlementUnitName: res.secondPartyName,
                        taxAmount: 0,
                        taxRate: res.taxRate,
                        totalAmount: 0
                    }
                })
                this.serviceFeeData.splice(index, 1, ...result)
            } else {
                // 如果选择的合同没有清单
                result = {
                    amount: 0,
                    billId: this.billid,
                    changeType: 1,
                    contractBillId: res.contractId,
                    contractBillNo: res.contractNumber,
                    contractDtlId: '',
                    contractDtlName: '',
                    dtlId: '',
                    invoiceNo: '',
                    price: 0,
                    quantity: '',
                    settlementUnitId: res.secondPartyId,
                    settlementUnitName: res.secondPartyName,
                    taxAmount: 0,
                    taxRate: res.taxRate,
                    totalAmount: 0
                }
                this.serviceFeeData[index] = result
            }
        },
        // 结算单位
        async billingUnitDialog (row, index) {
            this.jsdwIds = row.settlementUnitId
            let res = await request.getBillingUnit(this.jsdwData, this.jsdwIds)
            let result = {
                amount: 0,
                billId: this.billid,
                changeType: 1,
                contractBillId: '',
                contractBillNo: '',
                contractDtlId: '',
                contractDtlName: '',
                dtlId: '',
                invoiceNo: '',
                price: 0,
                quantity: 0,
                settlementUnitId: res.id,
                settlementUnitName: res.outerName,
                taxAmount: 0,
                taxRate: 0,
                totalAmount: 0
            }
            this.serviceFeeData[index] = result
        },
        // 复选框选中的数据
        serviceFeeSelect (selection) {
            this.serviceFeeList = selection
        },

        // 清单名称
        contractDtlNameBlur (row) {
            if (row.changeType == 1) {
                row.changeType == 1
            } else {
                row.changeType = 2
            }
        },
        // 数量变化时
        quantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (!!row.amount && !!row.quantity) {
                row.price = +row.amount / +row.quantity
            }
        },
        // 服务费用金额变化时
        amountFBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (!!row.amount && !!row.quantity) {
                row.price = +row.amount / +row.quantity
            }
            if (!!row.amount && !!row.taxRate) {
                row.taxAmount = row.amount * row.taxRate
            }
            if (!!row.amount && !!row.taxAmount) {
                row.totalAmount = row.amount + row.taxAmount
            }
        },
        // 编号变化时
        invoiceNoBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        // 税率变化时
        taxRateBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (!!row.amount && !!row.taxRate) {
                row.taxAmount = row.amount * row.taxRate
            }
        },
        //税额变化时
        taxAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            if (!!row.amount && !!row.taxAmount) {
                row.totalAmount = +row.amount + +row.taxAmount
            }
        },
        // 服务费用删除
        serviceFeeDelete (row) {
            console.log(row)

            row.changeType = -1

        },
        tableRowClassNameF ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        cellMouseEnterF (row) {
            this.MouseEnterIdF = row.billId
        },
        cellMouseLeaveF () {
            this.MouseEnterIdF = 0
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置验收明细-加工费有错误时在表格上面显示的错误信息
        setErrorProcessingFee (msg) {
            let index = this.errorProcessingFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorProcessingFeeMsg.push(msg)
            }
        },
        // 设置验收明细-成品明细有错误时在表格上面显示的错误信息
        setErrorFinishedProductMsg (msg) {
            let index = this.errorFinishedProductMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorFinishedProductMsg.push(msg)
            }
        },
        // 设置验收明细-原物资有错误时在表格上面显示的错误信息
        setErrorRawMaterialsMsg (msg) {
            let index = this.errorRawMaterialsMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorRawMaterialsMsg.push(msg)
            }
        },
        // 设置服务费用有错误时在表格上面显示的错误信息
        setErrorServiceFeeMsg (msg) {
            let index = this.errorServiceFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorServiceFeeMsg.push(msg)
            }
        },
        // 保存基本信息
        basicInfoSave () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        if (this.formData.redBillState == 3) {
                            this.redFormData.remarks =
                                this.formData.remarks
                        }
                        processingRequest
                            .basicInfoSave(
                                this.formData.redBillState == 3
                                    ? this.redFormData
                                    : this.formData
                            )
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },

        // 保存加工费
        saveProcessingFeeData () {
            this.errorProcessingFeeMsg = []
            return new Promise((resolve, reject) => {
                this.processingFeeData.forEach(its => {
                    its.children.forEach(item => {
                        !item.materialClassName
                            ? this.setErrorProcessingFee('请填写物资类别')
                            : ''
                        !item.materialName
                            ? this.setErrorProcessingFee('请填写物资名称')
                            : ''
                        // !item.unit ? this.setErrorProcessingFee('请填写单位') : ''
                        // !item.warehouseName
                        //     ? this.setErrorProcessingFee('请填写仓库')
                        //     : ''

                        // !item.quantity
                        //     ? this.setErrorProcessingFee('请填写数量')
                        //     : ''
                        // !item.price
                        //     ? this.setErrorProcessingFee('请填写加工单价(元)')
                        //     : ''
                        // !item.amount
                        //     ? this.setErrorProcessingFee('请填写金额(元)')
                        //     : ''
                    })
                })
                console.log(this.errorProcessingFeeMsg)
                if (this.errorProcessingFeeMsg.length > 0) {
                    this.setError('processingFee')
                    reject('验收明细错误')
                    return
                } else {
                    processingRequest
                        .saveProcessingFeeData(this.processingFeeData)
                        .then(() => {
                            this.clearError('processingFee')
                            resolve()
                        })
                        .catch(err => {
                            this.errorProcessingFeeMsg[0] = err.message
                            this.setError('processingFee')
                            reject(err)
                        })
                }

            })
        },
        // 保存成品明细
        saveFinishedProductData () {
            this.errorFinishedProductMsg = []
            return new Promise((resolve, reject) => {
                this.finishedProductData.forEach(its => {
                    its.children.forEach(item => {
                        !item.materialClassName
                            ? this.setErrorFinishedProductMsg('请填写物资类别')
                            : ''
                        !item.materialName
                            ? this.setErrorFinishedProductMsg('请填写物资名称')
                            : ''
                        // !item.unit ? this.setErrorFinishedProductMsg('请填写单位') : ''
                        // !item.warehouseName
                        //     ? this.setErrorFinishedProductMsg('请填写仓库')
                        //     : ''

                        // !item.quantity
                        //     ? this.setErrorFinishedProductMsg('请填写数量')
                        //     : ''
                        // !item.price
                        //     ? this.setErrorFinishedProductMsg('请填写成品单价(元)')
                        //     : ''
                        // !item.amount
                        //     ? this.setErrorFinishedProductMsg('请填写金额(元)')
                        //     : ''
                        // !item.apportionedFreight
                        //     ? this.setErrorFinishedProductMsg('请填写分摊服务费(元)')
                        //     : ''
                        // !item.totalAmortizationRatio
                        //     ? this.setErrorFinishedProductMsg('总摊销比例%')
                        //     : ''
                        // !item.amortizationMonth
                        //     ? this.setErrorFinishedProductMsg('摊销月')
                        //     : ''
                    })
                })
                console.log(this.errorFinishedProductMsg)
                if (this.errorFinishedProductMsg.length > 0) {
                    this.setError('finishedProductDetails')
                    reject('验收明细错误')
                    return
                } else {
                    processingRequest
                        .saveFinishedProductData(this.finishedProductData)
                        .then(() => {
                            this.clearError('finishedProductDetails')
                            resolve()
                        })
                        .catch(err => {
                            this.errorFinishedProductMsg[0] = err.message
                            this.setError('finishedProductDetails')
                            reject(err)
                        })
                }
            })
        },
        // 保存原物资
        saveRawMaterialsData () {
            console.log(this.rawMaterialsData)
            this.errorRawMaterialsMsg = []
            return new Promise((resolve, reject) => {
                console.log(this.rawMaterialsData.length)
                this.rawMaterialsData.forEach(its => {
                    its.children.forEach(item => {
                        !item.materialClassName
                            ? this.setErrorRawMaterialsMsg('请填写物资类别')
                            : ''
                        !item.materialName
                            ? this.setErrorRawMaterialsMsg('请填写物资名称')
                            : ''
                        !item.unit
                            ? this.setErrorRawMaterialsMsg('请填写单位')
                            : ''
                        // !item.warehouseName
                        //     ? this.setErrorRawMaterialsMsg('请填写仓库')
                        //     : ''

                        // !item.receivedQuantity
                        //     ? this.setErrorRawMaterialsMsg('请填写领用数量')
                        //     : ''
                        // !item.offsetInventoryQuantity
                        //     ? this.setErrorRawMaterialsMsg('请填写冲库存数量')
                        //     : ''
                        // !item.price
                        //     ? this.setErrorRawMaterialsMsg('请填写采购单价（元）')
                        //     : ''
                        // !item.amount
                        //     ? this.setErrorRawMaterialsMsg('请填写金额（元）')
                        //     : ''
                    })
                    console.log(this.errorRawMaterialsMsg)

                })
                if (this.errorRawMaterialsMsg.length > 0) {
                    this.setError('rawMaterials')
                    reject('验收明细错误')
                    return
                } else {
                    processingRequest
                        .saveRawMaterialsData(this.rawMaterialsData)
                        .then(() => {
                            this.clearError('rawMaterials')
                            resolve()
                        })
                        .catch(err => {
                            this.errorRawMaterialsMsg[0] = err.message
                            this.setError('rawMaterials')
                            reject(err)
                        })
                }
            })
        },
        // 保存服务费用
        saveServiceFeeData () {
            this.errorServiceFeeMsg = []
            return new Promise((resolve, reject) => {
                // 检测必填项是否全部填写完毕
                this.serviceFeeData.forEach(item => {
                    console.log(item)
                    // !item.settlementUnitName
                    //     ? this.setErrorServiceFeeMsg('请填写结算单位')
                    //     : ''
                    // !item.contractDtlName
                    //     ? this.setErrorServiceFeeMsg('请填写清单名称')
                    //     : ''
                    // !item.quantity
                    //     ? this.setErrorServiceFeeMsg('请填写数量')
                    //     : ''
                    // !item.price
                    //     ? this.setErrorServiceFeeMsg('请填写单价(元)')
                    //     : ''
                    // !item.amount
                    //     ? this.setErrorServiceFeeMsg('请填写金额(元)')
                    //     : ''
                    // !item.totalAmount
                    //     ? this.setErrorServiceFeeMsg('请填写税价合计(元)')
                    //     : ''
                })
                // this.setSelectedInfo(this.serviceFeeData)
                // openAppClient('/showSelectedData', '选择结果')
                if (this.errorServiceFeeMsg.length > 0) {
                    this.setError('transportationCharge')
                    reject('服务费用错误')
                    return
                } else {
                    // 如果必填项已全部填完,那么才发送保存服务费用的接口,如果报错依然需要定位到具体位置
                    processingRequest
                        .saveServiceFeeData(this.serviceFeeData)
                        .then(() => {
                            this.clearError('transportationCharge')
                            resolve()
                        })
                        .catch(err => {
                            this.errorServiceFeeMsg[0] = err.message
                            this.setError('transportationCharge')
                            reject(err)
                        })
                }
            })
        },

        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.basicInfoSave(),
                this.saveProcessingFeeData(),
                this.saveFinishedProductData(),
                this.saveRawMaterialsData(),
                this.saveServiceFeeData()
            ])
                .then(() => {
                    // hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.scorllError()
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 提交审核
        submitReview () {
            // 当原材料来源为“购买”，验收明细必须选择原材料
            if (
                this.formData.sourceOfRawMaterials == 1 &&
                this.rawMaterialsData.length < 1
            ) {
                this.clientPop(
                    'err',
                    `请再次确认原材料的来源是购买还是自有。
                ▷若是购买，则必须选择原材料，以冲抵原材料借方收入账；
                ▷若是自有，无需选择原材料，可在【基本信息】将原材料来源选择为自有。`
                )
                return
            }
            showLoading()
            this.errorList = []
            Promise.all([
                this.basicInfoSave(),
                this.saveProcessingFeeData(),
                this.saveFinishedProductData(),
                this.saveRawMaterialsData(),
                this.saveServiceFeeData()
            ])
                .then(() => {
                    request
                        .commitAudit(this.auditParams)
                        .then(() => {
                            this.clientPop('suc', '提交成功', this.handleClose)
                        })
                        .catch(() => {
                            this.clientPop('err', '提交失败', () => {
                                this.scorllError()
                            })
                        })
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.clientPop('err', '提交失败', () => {
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 撤销审核
        undoAudit () {
            this.clientPop('info', '确定返回上一步操作吗?', () => {
                showLoading()
                request
                    .undoAudit(this.auditParams)
                    .then(() => {
                        this.clientPop('suc', '撤回成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        basicInfoDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                () => {
                    showLoading()
                    console.log(request)
                    processingRequest
                        .basicInfoDelete(this.billid)
                        .then(() => {
                            this.clientPop('suc', '删除成功', this.handleClose)
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            )
        },
        // 打印
        async print (value) {
            const printData = async ()=>{
                showLoading()
                try{
                    const  params =  {
                        'reportTitle': '', //报表名
                        'orgName': this.formData.orgName, //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': this.formData.billNo, //单据编码
                        'summaryInfoItems': [], //基本信息
                        'tables': [] //表格
                    }
                    const reportTitle = this.commandList.find(item => item.key === value)
                    params.reportTitle = reportTitle.value
                    let tableObj = {}
                    if(reportTitle.key === 1 || reportTitle.key === 2) {
                        tableObj = {
                            1: this.ProcessingAcceptanceToPrn(),
                            2: this.FinishedPrinting()
                        }
                    }else {
                        tableObj = {
                            1: this.ProcessingAcceptanceToPrn(),
                            2: this.FinishedPrinting(),
                            3: this.servPrn()
                        }
                    }
                    const tableData = tableObj[reportTitle.key]
                    params.tables.push(tableData.tableList)
                    if(tableData.theScndTbl) {
                        params.tables.push(tableData.theScndTbl)
                    }
                    if(reportTitle.key !== 2) {
                        params.summaryInfoItems = tableData.basicInfo
                        params.tables.push(await this.prnAuditHst())
                    }
                    hideLoading()
                    return params
                }catch(err) {
                    console.log(err)
                    this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            const data = await printData()
            webprintReport(data)
        },
        // 委外加工物资验收单
        ProcessingAcceptanceToPrn () {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['加工单位', data.processingUnitName, false],
                ['附件', '    ' + '张', false],
                ['加工类型', ['普通加工', '砼加工'][data.businessType], false],
                ['验收依据', data.contractNo, false],
                ['税率(%)', data.taxRate + '%', false],
                ['验收日期', data.acceptanceDate, false],
                ['本期验收金额(元)', data.acceptanceAmount, false],
                ['可抵扣税额(元)', data.taxAmount, false],
                ['价税合计金额(元)', data.totalAmount, false],
                ['价税合计金额大写', numToChinese(Math.abs(data.totalAmount)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 加工费明细
            let newArr = this._.cloneDeep(this.processingFeeData)
            let lastArr = []
            newArr.forEach(item => {
                lastArr.push(item)
                if(item.children.length > 0) {
                    lastArr.push(...item.children)
                }
            })
            const tableList = {
                'tableTitle': '加工费明细',
                'tableContent': {
                    '物资类别': 'materialClassName',
                    '物资名称': 'materialName',
                    '规格': 'spec',
                    '材质': 'texture',
                    '单位': 'unit',
                    '验收数量': 'quantity',
                    '验收单价(元)': 'price',
                    '验收金额(元)': 'amount',
                },
                'tableData': lastArr, //表格数据
            }
            // 原物资明细
            let yaunwuziArr = this._.cloneDeep(this.rawMaterialsData)
            let rawMaterialsArr = []
            yaunwuziArr.forEach(item => {
                rawMaterialsArr.push(item)
                if(item.children.length > 0) {
                    rawMaterialsArr.push(...item.children)
                }
            })
            const theScndTbl = {
                'tableTitle': '原物资明细',
                'tableContent': {
                    '物资类别': 'materialClassName',
                    '物资名称': 'materialName',
                    '规格': 'spec',
                    '材质': 'texture',
                    '单位': 'unit',
                    '仓库': 'warehouseName',
                    '领用数量': 'receivedQuantity',
                    '冲库存数量': 'offsetInventoryQuantity',
                    '单价(元)': 'price',
                    '金额(元)': 'amount',
                },
                'tableData': rawMaterialsArr, //表格数据
            }
            return { basicInfo, tableList, theScndTbl }
        },
        // 成品物资明细
        FinishedPrinting () {
            // 表格数据
            let newArr = this._.cloneDeep(this.finishedProductData)
            let lastArr = []
            newArr.forEach(item => {
                lastArr.push(item)
                if(item.children.length > 0) {
                    lastArr.push(...item.children)
                }
            })
            const tableList = {
                'tableTitle': '成品物资明细',
                'tableContent': {
                    '物资类别': 'materialClassName',
                    '物资名称': 'materialName',
                    '规格': 'spec',
                    '材质': 'texture',
                    '单位': 'unit',
                    '仓库': 'warehouseName',
                    '数量': 'quantity',
                    '成品单价(元)': 'price',
                    '金额(元)': 'amount',
                },
                'tableData': lastArr, //表格数据
            }
            return { tableList }
        },
        // 服务费
        servPrn () {
            if(this.serviceFeeData.length > 0) {
                if(this.serviceFeeList.length < 1) {
                    this.serviceFeeList = this._.cloneDeep(this.serviceFeeData)
                    return this.FmtData(this.serviceFeeList)
                }else {
                    return this.FmtData(this.serviceFeeList)
                }
            }else {
                this.clientPop('err', '服务费用无明细可打印')
                return
            }
        },
        // 格式数据
        FmtData (data) {
            // 是否相同结算单位
            const isTheSm = data.some(item =>data[0].settlementUnitId !== item.settlementUnitId)
            // 是否相同税率
            const isSmRt = data.some(item =>data[0].taxRate !== item.taxRate)
            if(isTheSm || isSmRt) {
                this.clientPop('err', '需选择相同结算单位和相同税率的数据,请先选择!')
                return
            }else {
                // 如果都是相同结算单位并且相同税率
                const obj = data.reduce((prev, c) => {
                    prev.amount += +(+c.amount).toFixed(2),
                    prev.totalAmount += +(+c.totalAmount).toFixed(2),
                    prev.taxAmount += +(+c.taxAmount).toFixed(2)
                    return prev
                }, { amount: 0, totalAmount: 0, taxAmount: 0, })
                obj.settlementUnitName = data[0].settlementUnitName
                obj.contractBillNo = data[0].contractBillNo
                obj.taxRate = data[0].taxRate
                return this.servPrnSelectFn(obj)
            }
        },
        servPrnSelectFn (obj) {
            const basicInfo = []
            const data = this.formData
            const list = [
                ['服务单位', obj.settlementUnitName, false],
                ['附件', '    ' + '张', false],
                ['验收依据', obj.contractBillNo, false],
                ['验收日期', data.acceptanceDate, false],
                ['本期验收金额(元)', obj.amount, false],
                ['税率(%)', obj.taxRate + '%', false],
                ['可抵扣税额(元)', obj.taxAmount, false],
                ['价税合计金额(元)', obj.totalAmount, false],
                ['价税合计金额大写', numToChinese(Math.abs(obj.totalAmount)), true],
                ['备注信息', data.remarks, true],
            ]
            list.forEach(item => {
                const obj = {
                    label: '标题',
                    value: '内容',
                    isFullRow: false, // 是否占整行
                }
                obj.label = item[0]
                obj.value = item[1]
                obj.isFullRow = item[2]
                basicInfo.push(obj)
            })
            // 表格数据
            const tableList = {
                'tableTitle': '服务费明细',
                'tableContent': {
                    '结算单位': 'settlementUnitName',
                    '清单名称': 'contractDtlName',
                    '发票编号': 'invoiceNo',
                    '数量': 'quantity',
                    '单价(元)': 'price',
                    '金额': 'amount',
                    '税率': 'taxRate',
                    '税额': 'taxAmount',
                    '税额合计': 'totalAmount',
                },
                'tableData': this.serviceFeeList, //表格数据
            }
            return { basicInfo, tableList }
        },

        // 审核历史
        async prnAuditHst () {
            const historyTable  = await request.getAuditHistory(this.auditParams)
            const historyList = {
                'tableTitle': '审核历史',
                'tableContent': {
                    '审核级次': 'unitName',
                    '审核人': 'assignUser',
                    '审核人岗位': 'userTitle',
                    '通知时间': 'notifyTime',
                    '审核时间': 'completeTime',
                    '审核意见': 'opinion',
                },
                'tableData': historyTable, //表格数据
            }
            return historyList
        },

        // 点击冲红单
        async redSingle () {
            try {
                await processingRequest.isRedSingleFn(this.billid)
                this.$router.replace({
                    path: '/processCheckAdd',
                    query: { isRedSingle: '1', billid: this.billid }
                })
            }catch(err) {
                console.log(err)
            }
        },

        // --------------------------------下面按钮--------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await request.getCurrentUnitInfo(
                this.auditParams
            )
        },
        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.basicInfoDelete() // 删除
            }else if(arg.type === 'multiple') {
                this.print(arg.value) // 打印
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon') && this.historyData.length > 0) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        historyTableHeight (data) {
            this.historyData = data
        },

        //提交
        submit () {},
        //保存
        save () {},
        ctDelete () {
            showPromptPop(
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。'
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/materialsettle/processingAcceptance/delete',
                    params: {
                        id: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('./processCheck')
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        handleClose () {
            hideLoading()
            this.$router.replace('/processCheck')
        },

        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //日期转换格式
        getTime (dt) {
            var year = dt.getFullYear() //年
            var month = dt.getMonth() + 1 //月
            var date = dt.getDate() //日
            month = month < 10 ? '0' + month : month
            date = date < 10 ? '0' + date : date
            var str = year + '-' + month + '-' + date
            return str
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
.childTab {
    ::v-deep .el-tabs__header {
        position: absolute !important;
    }
    ::v-deep .el-tabs__content {
        padding: 0 0 0 20px !important;
    }
}
.childTab1 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}
.childTab2 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
::v-deep .drp {
    .el-button--small {
        border-radius: 3px;
        margin-right: 10px;
        padding: 7px 15px !important;
    }
}
::v-deep.el-table .warning-row {
    display: none;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
